function  CudaSlicePlot(handles, position)
% This function plots the 6 slices as subplot in the panel pointed by
% panelHandle

persistent data
persistent sizeI;
persistent sizeJ;
persistent MIN;
persistent MAX;
persistent previous_pos;
persistent lh;
if isempty(sizeI)
    sizeI = [0 0 0];
    sizeJ = [0 0 0];
    images = cell(6,1);
    MIN = [0; 0; 0; 0];
    MAX = [0; 0; 0; 0];
    previous_pos = [NaN NaN NaN];
end

sliceToPlot = [1 1 1];
for ind=1:3
    if previous_pos(ind)==position(ind)
        sliceToPlot(ind)=0;
    end
end
if max(sliceToPlot)==0
    sliceToPlot=[1 1 1];
end
previous_pos = position;

panelHandle = handles.plotPanel;
posHandle = handles.cursorPosition;
stack = get(panelHandle,'userdata');
if(isempty(stack)) return; end;
% Create subplots at first call / retrieve handles otherwise
children = (get(panelHandle,'children'));
children = flipud(children);
theta = get(handles.rotation,'userdata');
if isempty(theta)
    theta=0;
end
M = makehgtform('xrotate',theta);
if iscolumn(position)
    position = position';
end
real_p = position;
real_p=M * [real_p 1]';
real_p = real_p(1:3)';
real_p = round(real_p*1000)/1000;
set(posHandle,'data',position);
position=real_p;
%compute Talairach and MNI coordinates
M = get(handles.talairachTable,'userdata');
if ~isempty(M)
    [Pac,Pt] = Talairach(position,M);
    set(handles.talairachTable,'data',Pt);
    set(handles.mniTable,'data',Pac);
end
if ~isempty(get(handles.selectExcisionVolume,'tooltipstring'))    
    %pos = get(handles.cursorPosition,'data');
    pos = [Pt 1];
    stack = get(handles.plotPanel,'userdata');
    M = stack(8).mat;
    pos = M\pos';
    V = stack(8).vol;
    pos = int16(pos(1:3));
    try
        N = V(pos(1),pos(2),pos(3));
        if isempty(data)
            data = importdata([pwd '\templates\aal_labels.txt']);
        end
        if N~=0
            %name = data{N+1};
            name = data{N+1};
        else
            name = '';
        end
        set(handles.selectedArea,'string',{'Area:';[name]});
    catch
        set(handles.selectedArea,'string',{'Area:'});
    end
end

if isempty(children);
    sp = struct('z',[subplot(2,3,1,'Parent',panelHandle) subplot(2,3,4,'Parent',panelHandle)],...
                'y',[subplot(2,3,2,'Parent',panelHandle) subplot(2,3,5,'Parent',panelHandle)],...
                'x',[subplot(2,3,3,'Parent',panelHandle) subplot(2,3,6,'Parent',panelHandle)]);
    for j=1:2
        set(sp.x(j),'position', [0.67 1-0.5*j 0.32 0.5]);        
        set(sp.y(j),'position', [0.34 1-0.5*j 0.32 0.5]);
        set(sp.z(j),'position', [0.01 1-0.5*j 0.32 0.5]);
    end    
else
    sp = struct('z',children(1:2),'y',children(3:4),'x',children(5:6));
end
% get corner coordinates in real world units.
corners = zeros(4,8);
volSize = size(stack(1).vol);
for k1 = 0:1
    for k2 = 0:1
        for k3 = 0:1
            corners(:,k1*4+k2*2+k3+1) = stack(1).mat * [k1 * volSize(1) ; k2 * volSize(2) ; k3 * volSize(3) ; 1];
        end
    end
end        
new_MIN = min(corners,[],2);
new_MAX = max(corners,[],2);
if any( (MIN ~= new_MIN) | (MAX ~= new_MAX) ) 
    MIN=new_MIN;
    MAX=new_MAX;      
    for k=1:2
        axis(sp.z(k),'image',[MIN(1) MAX(1) MIN(2) MAX(2)]);
        axis(sp.y(k),'image',[MIN(1) MAX(1) MIN(3) MAX(3)]);    
        axis(sp.x(k),'image',[MIN(2) MAX(2) MIN(3) MAX(3)]); 
    end
end

for j=1:2 % plot up first then bottom with only IRM
    if sliceToPlot(3)
    cla(sp.z(j));
    Draw(0,'Z',3,1,2,sp.z,false);
    else
    delete (lh(j,5));
    delete(lh(j,6));
    end
    if sliceToPlot(2)
    cla(sp.y(j));
    Draw(1,'Y',2,1,3,sp.y,false);
    else
    delete (lh(j,3));
    delete(lh(j,4));
    end
    if sliceToPlot(1)
    cla(sp.x(j));
    Draw(2,'X',1,2,3,sp.x,true);  
    else
    delete (lh(j,1));
    delete(lh(j,2));
    end
    set(sp.x(j),'Xdir','reverse','xticklabel',[],'yticklabel',[],'color','black');
    set(sp.y(j),'xticklabel',[],'yticklabel',[],'color','black');
    set(sp.z(j),'xticklabel',[],'yticklabel',[],'color','black');
    % Draw lines and print labels
    margin = 0.01;
    fontSize = 0.03;
    set(gcf,'currentAxes', sp.x(j));   
    lh(j,1) = line([MIN(2) MAX(2)],[position(3) position(3)], 'hitTest','off',...
        'linestyle',':','color','blue','LineWidth',1);
    lh(j,2) = line([position(2) position(2)],[MIN(3) MAX(3)], 'hitTest','off',...
        'linestyle',':','color','blue');
    text('Units', 'normalized', 'Position', [margin 1],...
        'String','F', 'Color', 'blue', 'FontUnits', 'normalized',...
        'FontSize', fontSize,'VerticalAlignment', 'top')
    text('Units', 'normalized', 'Position', [0.5 1],...
        'String','Sagittal', 'Color', 'blue', 'FontUnits', 'normalized',...
        'FontSize', fontSize, 'HorizontalAlignment', 'center','VerticalAlignment', 'top')
    text('Units', 'normalized', 'Position', [(1-margin) 1],...
        'String','B', 'Color', 'blue', 'FontUnits', 'normalized',...
        'FontSize', fontSize, 'HorizontalAlignment', 'right','VerticalAlignment', 'top')
    set(gcf,'currentAxes', sp.y(j));
    lh(j,3) = line([MIN(1) MAX(1)],[position(3) position(3)], 'hitTest','off',...
        'linestyle',':','color','blue');
    lh(j,4) = line([position(1) position(1)],[MIN(3) MAX(3)], 'hitTest','off',...
        'linestyle',':','color','blue');
    text('Units', 'normalized', 'Position', [margin 1],...
        'String','L', 'Color', 'blue', 'FontUnits', 'normalized',...
        'FontSize', fontSize,'VerticalAlignment', 'top')
    text('Units', 'normalized', 'Position', [0.5 1],...
        'String','Frontal', 'Color', 'blue', 'FontUnits', 'normalized',...
        'FontSize', fontSize, 'HorizontalAlignment', 'center','VerticalAlignment', 'top')
    text('Units', 'normalized', 'Position', [(1-margin) 1],...
        'String','R', 'Color', 'blue', 'FontUnits', 'normalized',...
        'FontSize', fontSize, 'HorizontalAlignment', 'right','VerticalAlignment', 'top')
    set(gcf,'currentAxes', sp.z(j));
    lh(j,5) = line([MIN(1) MAX(1)],[position(2) position(2)], 'hitTest','off',...
        'linestyle',':','color','blue');
    lh(j,6) = line([position(1) position(1)],[MIN(2) MAX(2)], 'hitTest','off',...
        'linestyle',':','color','blue');
    text('Units', 'normalized', 'Position', [margin 1],...
        'String','L', 'Color', 'blue', 'FontUnits', 'normalized',...
        'FontSize', fontSize,'VerticalAlignment', 'top')
    text('Units', 'normalized', 'Position', [0.5 1],...
        'String','Axial', 'Color', 'blue', 'FontUnits', 'normalized',...
        'FontSize', fontSize, 'HorizontalAlignment', 'center','VerticalAlignment', 'top')
    text('Units', 'normalized', 'Position', [(1-margin) 1],...
        'String','R', 'Color', 'blue', 'FontUnits', 'normalized',...
        'FontSize', fontSize, 'HorizontalAlignment', 'right','VerticalAlignment', 'top')
end
colorbar('peer',sp.x(1),'off');
if get(handles.displayfMRI,'value')    
    DisplayfMRIColorbar();
end
function Draw(dir,c,d,e,f,g,trans)
    px = libpointer('int32Ptr',0);
    py = libpointer('int32Ptr',0);
    calllib('cudaicem','GetSliceSize',dir,px,py);
    if px.value~= sizeI(dir+1) || py.value ~= sizeJ(dir+1)
       images{dir*2+j} = libpointer('uint8PtrPtr',zeros(px.value*py.value*3,1));
    end
    if j==1
        calllib('cudaicem','GetSlice',position,dir,images{dir*2+j});
    elseif j==2
        calllib('cudaicem','GetFirstSlice',position,dir,images{dir*2+j});
    end
    p=images{dir*2+j};
    if trans
        dx = px.value;
        dy = py.value;
    else
        dx = py.value;
        dy = px.value;
    end
    RGBim = reshape(permute(reshape(p.value,3,dy,dx),[2 3 1]),dx,dy,3);
    image('parent',g(j),'XData', [MIN(e) MAX(e)],'YData', [MIN(f) MAX(f)],...
          'CData',RGBim,'ButtonDownFcn',{@SetPosition,c,position(d),handles});
end

function DisplayfMRIColorbar()
    fMRI_cm = handles.fMRIColormap;
    cm = get(fMRI_cm,'string');
    cm = lower(cm{get(fMRI_cm,'value')});
    cm = eval([cm '(256)']);
    colormap(cm);
    hcb=colorbar('peer',sp.x(1),'SouthOutside');
    cb_pos = get(hcb,'position');
    cb_pos(4)=cb_pos(4)/4;
    tick = get(hcb,'ytick');
    minmax_fMRI = stack(10).minmax;
    min_fMRI = minmax_fMRI(1);
    max_fMRI = minmax_fMRI(2);
    for i=1:length(tick)
     tickLabel{i} = num2str(int32(min_fMRI + (tick(i)/256) * (max_fMRI-min_fMRI)));
    end
    set(hcb,'position',cb_pos);
end

end



function SetPosition(src,event,type,offset,handles)
% src is image handle
% src.parent is the subplot
% src.parent.parent is the plotPanel
if strcmp(get(gcf,'selectionType'),'alt')
    f = figure('name','Full Screen');
    h = copyobj(get(src,'parent'),f);
    set(h,'position',[0 0 1 1]);
    images = get(h,'children');
    for i=1:length(get(h,'children'))
        set(images(i),'buttondownfcn',[]);
    end        
    delete(images(1));
    delete(images(2));
else
    pos = get(get(src,'parent'),'CurrentPoint');
    pos = round(10*pos) / 10;
    pos = pos(1,1:2);
    switch type
        case 'X'
            newPosition = [offset pos(1) pos(2)];
        case 'Y'
            newPosition = [pos(1) offset pos(2)];
        case 'Z'
            newPosition = [pos(1) pos(2) offset];
    end    
    theta = get(handles.rotation,'userdata');
    if isempty(theta)
        theta = 0;
    end
    M = makehgtform('xrotate',theta);
    newPosition =M \ [newPosition 1]';
    newPosition = newPosition(1:3);
    mainFigureHandle = get(get(get(src,'parent'),'parent'),'parent');
    props.WindowButtonMotionFcn = get(mainFigureHandle,'WindowButtonMotionFcn');
    props.WindowButtonUpFcn = get(mainFigureHandle,'WindowButtonUpFcn');
    setappdata(mainFigureHandle,'TestGuiCallbacks',props);    
    set(mainFigureHandle,'WindowButtonMotionFcn',{@wbm,type,offset,get(src,'parent'),handles})
    set(mainFigureHandle,'WindowButtonUpFcn',{@wbu})
    SlicePlot(handles,newPosition);
end
end
% get the values and store them in the figure's appdata
% set the new values for the WindowButtonMotionFcn and
% WindowButtonUpFcn




% ---------------------------
function wbm(h,evd,type,offset,imageHandle,handles)
% executes while the mouse moves
 pos = get(imageHandle,'CurrentPoint');
 pos = round(10*pos) / 10;
    pos = pos(1,1:2);
    switch type
        case 'X'
            newPosition = [offset pos(1) pos(2)];
        case 'Y'
            newPosition = [pos(1) offset pos(2)];
        case 'Z'
            newPosition = [pos(1) pos(2) offset];
    end
    theta = get(handles.rotation,'userdata');
    if isempty(theta)
        theta = 0;
    end
    M = makehgtform('xrotate',theta);
    newPosition =M \ [newPosition 1]';
    newPosition = newPosition(1:3);
    SlicePlot(handles,newPosition);
end


% ---------------------------
function wbu(h,evd)
% executes when the mouse button is released
% get the properties and restore them
props = getappdata(h,'TestGuiCallbacks');
set(h,props);
end